package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.RecordUsername_RVAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.DemoCache;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.IsBindingBean;
import com.beiing.tianshuai.tianshuai.entity.LoginBean;
import com.beiing.tianshuai.tianshuai.entity.QQUserInfoBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.LoginRecordDao;
import com.beiing.tianshuai.tianshuai.mine.presenter.LoginPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.LoginViewImpl;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.nim.config.preference.Preferences;
import com.beiing.tianshuai.tianshuai.nim.config.preference.UserPreferences;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.MD5Utils;
import com.beiing.tianshuai.tianshuai.util.RegexUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.google.gson.Gson;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.utils.Log;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

import static com.beiing.tianshuai.tianshuai.app.AppConstant.MSG_SET_ALIAS;

public class LoginActivity extends BaseActivity implements LoginViewImpl {

    private static final String TAG = "LoginActivity";
    private Unbinder mUnbinder;
    private Context mContext;
    private LoginPresenter mPresenter;
    // ======================== QQ =======================

    /**
     * qq主操作对象
     */
    private Tencent mTencent;

    /**
     * 授权登录监听器
     */
    private BaseUiListener loginListener;

    /**
     * 记录登陆网络请求重连次数
     */
    private int retryConnectLogin;
    private List<String> loginRecordList;
    private RecordUsername_RVAdapter recordAdapter;
    private LoginRecordDao recordDao;
    private PopupWindow popupWindow;

    @BindView(R.id.toolbar_iv_back)
    ImageButton mBack;                                  // 返回
    @BindView(R.id.btn_forget_password)
    TextView mForgetPass;                               // 忘记密码
    @BindView(R.id.btn_sign_up)
    TextView mSignUp;                                   // 注册
    @BindView(R.id.btn_login)
    TextView mLogin;                                    // 登陆
    @BindView(R.id.edit_login_username)
    EditText mUsername;                                 // 账号
    @BindView(R.id.edit_login_password)
    EditText mPassword;                                 // 密码
    @BindView(R.id.tv_qq_login)
    TextView mBtnQQLogin;                              // QQ登录
    @BindView(R.id.tv_wechat_login)
    TextView mBtnWeChatLogin;                          // 微信登录
    @BindView(R.id.rl_login_username)
    LinearLayout rlLoginUsername;
    @BindView(R.id.iv_choose)
    ImageView ivChooseUsername;                         //选择历史用户名
    @BindView(R.id.iv_delete_username)
    ImageView ivDeleteUsername;                         //删除用户名
    @BindView(R.id.iv_delete_password)
    ImageView ivDeletePassword;                         //删除密码

    /**
     * 是否是QQ登录绑定成功，如果绑定成功直接登录
     */
    private Boolean isQQBinding;

    public static void star(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void init() {
        mContext = this;
        mUnbinder = ButterKnife.bind(this);
        loginListener = new BaseUiListener();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        LogUtil.i(TAG, "bundle为空" + bundle);
        if (bundle != null) {
            LogUtil.i(TAG, "bundle不为空" + bundle);
            //空指针
            isQQBinding = bundle.getBoolean("isQQBinding", false);
            if (isQQBinding) {
                //QQLogin();
                ///Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
            }
        }
        initLoginRecord();
        initPresenter();
        initListener();
    }

    private void initLoginRecord() {
        loginRecordList = new ArrayList<>();
        recordDao = new LoginRecordDao(mContext);
        if (!recordDao.getRecordsList().isEmpty()) {
            loginRecordList.clear();
            loginRecordList.addAll(recordDao.getRecordsList());
            mUsername.setText(recordDao.getRecordsList().get(recordDao.getRecordsList().size() - 1));
            ivDeleteUsername.setVisibility(View.VISIBLE);
            ivChooseUsername.setVisibility(View.VISIBLE);
        }
        popupWindow = new PopupWindow(mContext);
    }

    private void initListener() {
        // 返回
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // 忘记密码
        mForgetPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ForgetPasswordActivity.class);
                startActivity(intent);
            }
        });

        // 去注册按钮
        mSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, SignUpEnterTelActivity.class);
                startActivity(intent);
            }
        });

        // 登陆按钮
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });

        // 微信登陆
        mBtnWeChatLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WXLogin();
            }
        });

        // QQ登陆
        mBtnQQLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                QQLogin();
            }
        });

        //选择用户名
        ivChooseUsername.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.setOutsideTouchable(false);
                if (!popupWindow.isShowing()) {
                    showPopupWindow();
                } else {
                    popupWindow.dismiss();
                }
            }
        });

        //用户名输入内容监听
        mUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    ivDeleteUsername.setVisibility(View.VISIBLE);
                } else {
                    ivDeleteUsername.setVisibility(View.GONE);
                }
            }
        });

        //密码输入监听
        mPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    ivDeletePassword.setVisibility(View.VISIBLE);
                } else {
                    ivDeletePassword.setVisibility(View.GONE);
                }
            }
        });

        //删除用户名
        ivDeleteUsername.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mUsername.setText("");
            }
        });

        //删除密码
        ivDeletePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPassword.setText("");
            }
        });
    }

    private void showPopupWindow() {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.popwin_record_username, null);
        initRecyclerView(contentView);
        popupWindow.setContentView(contentView);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(rlLoginUsername.getWidth());
        Drawable drawableBg = mContext.getResources().getDrawable(R.drawable.login_record);
        popupWindow.setBackgroundDrawable(drawableBg);
        popupWindow.showAsDropDown(rlLoginUsername);
    }

    private void initRecyclerView(View view) {
        recordAdapter = new RecordUsername_RVAdapter(mContext, loginRecordList);
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        RecyclerView recyclerView = view.findViewById(R.id.rv_record_username);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(recordAdapter);
        recyclerView.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                        ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
        recordAdapter.setOnClickCallBack(new RecordUsername_RVAdapter.OnClickCallBack() {
            @Override
            public void onItemClick(View view, int position, List<String> recordList) {
                mUsername.setText(recordList.get(position));
                popupWindow.dismiss();
            }

            @Override
            public void onDeleteClick(View view, int position, List<String> recordList) {
                recordDao.deleteRecord(recordList.get(position));
                recordAdapter.removeItem(position);
            }
        });
    }

    private void login() {
        String username = mUsername.getText().toString().trim();
        String password = mPassword.getText().toString().trim();
        //手机号码格式校验
//        if (RegexUtils.checkMobile(username)) {
//            //正确
//        } else {
//            showShortText("请输入正确的手机号");
//            return;
//        }
        //密码格式校验
        if (password.length() < 6) {
            showShortText("请输入完整的密码");
        }

        //登录 进行网络判断
        if (isEditComplete(username, password)) {
            LogUtil.i(TAG, "登录" + username + " " + password);
            mPresenter.getLoginResult(username, MD5Utils.getMd5Value(password));
        }
    }

    /**
     * 判断是否完成用户名和密码的输入
     *
     * @param username 用户名
     * @param password 密码
     * @return 是否输入完整
     */
    private boolean isEditComplete(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            showShortText("请输入账号");
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            showShortText("请输入密码");
            return false;
        }
        return true;
    }

    private void initPresenter() {
        mPresenter = new LoginPresenter(this);
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "登陆中...", false);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(LoginBean bean) {
        LogUtils.i(String.valueOf(bean.getCode()) + "\n" + bean.getData().toString(), TAG);
        switch (bean.getCode()) {
            case 200:
                showShortText("登陆成功");
                LoginBean.DataBean data = bean.getData();
                String uid = data.getUid();
                SPUtils.put(mContext, "uid", uid);
                SPUtils.put(mContext, "sex", data.getSex());
                SPUtils.put(mContext, "photo", data.getPhoto());
                SPUtils.put(mContext, "tel", data.getTel());
                SPUtils.put(mContext, "status", data.getStatus());
                SPUtils.put(mContext, "name", data.getName());
                SPUtils.put(mContext, "email", data.getEmail());
                SPUtils.put(mContext, "unit", data.getUnit());
                SPUtils.put(mContext, "identification_status", data.getAttestaction());
                SPUtils.put(mContext, "token", data.getToken());
                boolean hasData = recordDao.isHasRecord(data.getTel());
                if (!hasData) {
                    recordDao.addRecords(data.getTel());
                } else {
                    recordDao.deleteRecord(data.getTel());
                    recordDao.addRecords(data.getTel());
                }

                //设置极光推送别名
                JPushInterface.setAlias(mContext, MSG_SET_ALIAS, uid);
                //登录即时通讯
                loginWithNim(uid, data.getToken());

                break;
            case 401:
                showShortText("用户不存在");
                break;
            case 402:
                showShortText("密码错误");
                break;
            default:
                showShortText("登陆失败");
                break;
        }
    }

    /**
     * 登陆网易云信
     */
    private void loginWithNim(String uid, String token) {
        // 登陆网易云信
        LoginInfo loginInfo = new LoginInfo(uid, token);
        NimUIKit.login(loginInfo, new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                DemoCache.setAccount(loginInfo.getAccount());
                saveLoginInfo(loginInfo.getAccount(), loginInfo.getToken());
                // 初始化消息提醒配置
                initNotificationConfig();
                finish();
            }

            @Override
            public void onFailed(int i) {
                LogUtils.e("登陆网易云信失败 code:" + i, TAG);
                finish();
            }

            @Override
            public void onException(Throwable throwable) {
                LogUtils.e(throwable.getMessage(), TAG);
                finish();
            }
        });
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    private void initNotificationConfig() {
        // 初始化消息提醒
        NIMClient.toggleNotification(UserPreferences.getNotificationToggle());

        // 加载状态栏配置
        StatusBarNotificationConfig statusBarNotificationConfig = UserPreferences.getStatusConfig();
        if (statusBarNotificationConfig == null) {
            statusBarNotificationConfig = DemoCache.getNotificationConfig();
            UserPreferences.setStatusConfig(statusBarNotificationConfig);
        }
        // 更新配置
        NIMClient.updateStatusBarNotificationConfig(statusBarNotificationConfig);
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.toString(), TAG);
        if ((retryConnectLogin < 5)) {
            retryConnectLogin++;
            login();
        } else {
            retryConnectLogin = 0;
            showShortText("登陆请求失败");
        }
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        CustomProgressDialog.stopLoading();
        super.onDestroy();
    }

    /**
     * 登录微信
     */
    private void WXLogin() {
        CustomProgressDialog.showLoading(mContext, "正在登录，请稍后...", false);
        IWXAPI WXapi = WXAPIFactory.createWXAPI(this, AppConstant.WX_APP_ID, true);
        WXapi.registerApp(AppConstant.WX_APP_ID);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo";
        WXapi.sendReq(req);
        finish();
    }

    /**
     * QQ登录
     */
    private void QQLogin() {
        CustomProgressDialog.showLoading(mContext, "正在登录，请稍后...", false);
        mTencent = Tencent.createInstance(AppConstant.QQ_APP_ID, this.getApplicationContext());
        //要所有权限，不然会再次申请增量权限，这里不要设置成get_user_info,add_t
        String scope = "all";
        mTencent.login(this, scope, loginListener);
    }

    /**
     * 接收回跳的返回码
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //showShortText("result接收返回结果" + requestCode + resultCode + data);
        LogUtil.i(TAG, "result接收返回结果" + requestCode + resultCode + data);
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        }
        //如果绑定成功就直接登录
        if (requestCode == AppConstant.REQUEST_BUNDLE_SUCCESS) {
            if (resultCode == AppConstant.RESULT_BUNDLE_SUCCESS) {
                String tel = data.getStringExtra("tel");
                String pass = data.getStringExtra("pass");
                LogUtil.i(TAG, "绑定成功接收返回码" + tel + " " + pass);
                mPresenter.getLoginResult(tel, pass);

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            LogUtil.e(TAG, "微信response:" + response);
            JSONObject obj = (JSONObject) response;
            try {
                final String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                String s = obj.toString();
                Log.e(TAG, "登录成功" + s);
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken, expires);
                QQToken qqToken = mTencent.getQQToken();
                UserInfo userInfo = new UserInfo(getApplicationContext(), qqToken);
                userInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        Log.e(TAG, "登录成功" + response.toString());
                        Gson gson = new Gson();

                        QQUserInfoBean userInfoBean = gson.fromJson(response.toString(), QQUserInfoBean.class);
                        isBinding(openID, userInfoBean);
                    }

                    @Override
                    public void onError(UiError uiError) {
                        showShortText("登录失败" + uiError.toString());
                        Log.e(TAG, "登录失败" + uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        Log.e(TAG, "登录取消");
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            showShortText("授权失败");

        }

        @Override
        public void onCancel() {
            showShortText("授权取消");
        }
    }

    /**
     * 判断用户是否绑定手机号码
     *
     * @param unionId      用户唯一标识
     * @param userInfoBean 用户数据
     */
    private void isBinding(final String unionId, final QQUserInfoBean userInfoBean) {
        LogUtils.i(unionId, TAG);
        DisposableObserver<IsBindingBean> observer = new DisposableObserver<IsBindingBean>() {
            @Override
            public void onNext(@NonNull IsBindingBean bean) {
                int code = bean.getCode();
                //showShortText("返回码" + code);
                LogUtil.i(TAG, "返回码" + code);
                switch (code) {
                    case 200:
                        IsBindingBean.DataBean.NumberBean userBean = bean.getData().getNumber();
                        String uid = userBean.getUid();
                        SPUtils.put(mContext, "uid", uid);
                        SPUtils.put(mContext, "sex", userBean.getSex());
                        SPUtils.put(mContext, "photo", userBean.getPhoto());
                        SPUtils.put(mContext, "tel", userBean.getTel());
                        SPUtils.put(mContext, "status", userBean.getStatus());
                        SPUtils.put(mContext, "name", userBean.getName());
                        SPUtils.put(mContext, "email", userBean.getEmail());
                        SPUtils.put(mContext, "unit", userBean.getUnit());
                        SPUtils.put(mContext, "token", userBean.getToken());
                        SPUtils.put(mContext, "identification_status", userBean.getAttestaction());
                        showShortText("登录成功");

                        //设置极光推送
                        JPushInterface.setAlias(mContext, MSG_SET_ALIAS, uid);
                        //登录即时通讯
                        loginWithNim(uid, userBean.getToken());

                        finish();
                        break;
                    case 400:
                        showShortText("请先绑定手机号");
                        LogUtil.i(TAG, "请先绑定手机号");
                        Intent binding = new Intent(mContext, BindingActivity.class);
                        binding.putExtra("unionId", unionId);
                        binding.putExtra("nickName", userInfoBean.getNickname());
                        binding.putExtra("avatarUrl", userInfoBean.getFigureurlQq2());
                        binding.putExtra("platform", "qq_android");
                        //startActivity(binding); 请求码
                        startActivityForResult(binding, AppConstant.REQUEST_BUNDLE_SUCCESS);
                        //关闭登录界面，进入绑定界面，绑定成功后重新开启登录界面，
                        //理想状态，应该是QQ登录获取数据后就保持数据，绑定成功后就使用QQ数据直接登录
                        //如果杀死登录界面，QQ数据丢失，需要再次登录
                        //finish();
                        break;
                    case 401:
                        showShortText("请先绑定手机号");
                        break;
                    default:
                        showShortText("登录异常");
                        break;
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtils.e(e.toString(), TAG);
            }

            @Override
            public void onComplete() {
                CustomProgressDialog.stopLoading();
            }
        };

        DataManager.isBinding(unionId, "qq_android")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Override
    protected void onPause() {
        CustomProgressDialog.stopLoading();
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
            finish();
        }
    }
}
